// eslint-disable-next-line
import * as loginService from '@/api/login'
// eslint-disable-next-line
import { BasicLayout, BlankLayout, PageView, RouteView } from '@/layouts'

import { bxAnaalyse } from '@/core/icons'

import store from '../store'
import storage from 'store'

// 前端路由表 (基于动态)
const constantRouterComponents = {
  // 基础页面 layout 必须引入
  BasicLayout: BasicLayout,
  BlankLayout: BlankLayout,
  RouteView: RouteView,
  PageView: PageView,
  '403': () => import(/* webpackChunkName: "error" */ '@/views/exception/403'),
  '404': () => import(/* webpackChunkName: "error" */ '@/views/exception/404'),
  '500': () => import(/* webpackChunkName: "error" */ '@/views/exception/500'),

  // 你需要动态引入的页面组件
  Workplace: () => import('@/views/dashboard/Workplace'),
  Analysis: () => import('@/views/dashboard/Analysis'),

  // form
  BasicForm: () => import('@/views/form/basicForm'),
  StepForm: () => import('@/views/form/stepForm/StepForm'),
  AdvanceForm: () => import('@/views/form/advancedForm/AdvancedForm'),

  // list
  TableList: () => import('@/views/list/TableList'),
  StandardList: () => import('@/views/list/BasicList'),
  CardList: () => import('@/views/list/CardList'),
  SearchLayout: () => import('@/views/list/search/SearchLayout'),
  SearchArticles: () => import('@/views/list/search/Article'),
  SearchProjects: () => import('@/views/list/search/Projects'),
  SearchApplications: () => import('@/views/list/search/Applications'),
  ProfileBasic: () => import('@/views/profile/basic'),
  ProfileAdvanced: () => import('@/views/profile/advanced/Advanced'),

  // result
  ResultSuccess: () => import(/* webpackChunkName: "result" */ '@/views/result/Success'),
  ResultFail: () => import(/* webpackChunkName: "result" */ '@/views/result/Error'),

  // exception
  Exception403: () => import(/* webpackChunkName: "fail" */ '@/views/exception/403'),
  Exception404: () => import(/* webpackChunkName: "fail" */ '@/views/exception/404'),
  Exception500: () => import(/* webpackChunkName: "fail" */ '@/views/exception/500'),

  // account
  AccountCenter: () => import('@/views/account/center'),
  AccountSettings: () => import('@/views/account/settings/Index'),
  BasicSetting: () => import('@/views/account/settings/BasicSetting'),
  SecuritySettings: () => import('@/views/account/settings/Security'),
  CustomSettings: () => import('@/views/account/settings/Custom'),
  BindingSettings: () => import('@/views/account/settings/Binding'),
  NotificationSettings: () => import('@/views/account/settings/Notification'),

  // 'TestWork': () => import(/* webpackChunkName: "TestWork" */ '@/views/dashboard/TestWork')
}

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*',
  redirect: '/404',
  hidden: true
}
// 前端未找到页面路由（固定不用改）
const homeRouter = {
  path: '/dashboard',
  redirect: '/dashboard/Workplace',
  hidden: true
}

// 根级菜单
const rootRouter = {
  path: '/',
    name: 'index',
    component: BasicLayout,
    meta: { title: 'menu.home' },
    redirect: '/dashboard/workplace',
    children: [
      // dashboard
      // {
      //   path: '/dashboard',
      //   name: 'dashboard',
      //   redirect: '/dashboard/workplace',
      //   component: RouteView,
      //   meta: { title: 'menu.dashboard', keepAlive: true, icon: bxAnaalyse, permission: ['dashboard'] },
      //   children: [
      //     {
      //       path: '/dashboard/workplace',
      //       name: 'workplace',
      //       component: () => import('@/views/dashboard/Workplace'),
      //       meta: { title: 'menu.dashboard.workplace', keepAlive: true, permission: ['dashboard'] }
      //     }
      //   ]
      // },
      {
        path: '/dashboard/workplace',
        name: 'workplace',
        component: () => import('@/views/dashboard/Workplace'),
        meta: { title: 'menu.dashboard.workplace', keepAlive: true, permission: ['dashboard'] }
      }
    ]

}
// export const rootRouter=[
//   {
//     "path": "/",
//         component: BasicLayout,
//         "name": "index",
//         "meta": {
//             "keepAlive": false,
//             "permission": [
//                 "dashboard"
//             ]
//         },
//         "redirect": "/device/showlist",
//         "children": [
//             {
//                 "path": "/device",
//                 "name": "device",
//                 component: RouteView,
//                 "meta": {
//                     "title": "设备管理",
//                     "keepAlive": false,
//                     "permission": [
//                         "dashboard"
//                     ]
//                 },
//                 "children": [
//                     {
//                         "path": "/device/showlist",
//                         "name": "showlist",
//                         "meta": {
//                             "title": "显示列表",
//                             "keepAlive": false,
//                             "permission": [
//                                 "dashboard"
//                             ]
//                         }
//                     },
//                     {
//                         "path": "/device/devicelist",
//                         "name": "devicelist",
//                         component: () => import('@/views/device/Devicelist'),
//                         "meta": {
//                             "title": "设备管理",
//                             "keepAlive": false,
//                             "permission": [
//                                 "dashboard"
//                             ]
//                         }
//                     },
//                   ]
//             },
//           ]
//         },
//   {
//     path: '*',
//     redirect: '/404',
//     hidden: true
//   }
// ]
// export const rootRouter = [
//   {
//     path: '/',
//     name: 'index',
//     component: BasicLayout,
//     meta: { title: 'menu.home' },
//     redirect: '/dashboard/workplace',
//     children: [
//       // dashboard
//       {
//         path: '/dashboard',
//         name: 'dashboard',
//         redirect: '/dashboard/workplace',
//         component: RouteView,
//         meta: { title: 'menu.dashboard', keepAlive: true, icon: bxAnaalyse, permission: ['dashboard'] },
//         children: [
//           {
//             path: '/dashboard/analysis/:pageNo([1-9]\\d*)?',
//             name: 'analysis',
//             component: () => import('@/views/dashboard/Analysis'),
//             meta: { title: 'menu.dashboard.analysis', keepAlive: false, permission: ['dashboard'] }
//           },
//           {
//             path: '/dashboard/workplace',
//             name: 'workplace',
//             component: () => import('@/views/dashboard/Workplace'),
//             meta: { title: 'menu.dashboard.workplace', keepAlive: true, permission: ['dashboard'] }
//           }
//         ]
//       },
//       // device
//       {
//         path: '/device',
//         name: 'device',
//         redirect: '/device/Devicelist',
//         component: RouteView,
//         meta: { title: 'menu.device', icon: 'form', permission: ['dashboard'] },
//         children: [
//           {
//             path: '/device/Showlist',
//             name: 'showlist',
//             component: () => import('@/views/device/Showlist'),
//             meta: { title: 'menu.device.showlist', keepAlive: false, permission: ['dashboard'] }
//           },
//           {
//             path: '/device/devicelist',
//             name: 'devicelist',
//             component: () => import('@/views/device/Devicelist'),
//             meta: { title: 'menu.device.devicelist', keepAlive: false, permission: ['dashboard'] }
//           },
//           {
//             path: '/device/historylist',
//             name: 'historylist',
//             component: () => import('@/views/device/Historylist'),
//             meta: { title: 'menu.device.historylist', keepAlive: false, permission: ['dashboard'] }
//           },
//           {
//             path: '/device/curveanalysis',
//             name: 'devicelist',
//             component: () => import('@/views/device/Curveanalysis'),
//             meta: { title: 'menu.device.curveanalysis', keepAlive: false, permission: ['dashboard'] }
//           },
//           {
//             path: '/device/devicehistory',
//             name: 'devicehistory',
//             component: () => import('@/views/device/Devicehistory'),
//             meta: { title: 'menu.device.devicehistory', keepAlive: false, permission: ['dashboard'] }
//           },
//           {
//             path: '/device/solarController',
//             name: 'solarController',
//             component: () => import('@/views/device/SolarController'),
//             meta: { title: 'menu.device.solarController', keepAlive: false, permission: ['dashboard'] }
//           },
//           {
//             path: '/device/statistics',
//             name: 'statistics',
//             component: () => import('@/views/device/Statistics'),
//             meta: { title: 'menu.device.statistics', keepAlive: false, permission: ['dashboard'] }
//           },
//           {
//             path: '/device/grouplist',
//             name: 'grouplist',
//             component: () => import('@/views/device/Grouplist'),
//             meta: { title: 'menu.device.grouplist', keepAlive: false, permission: ['dashboard'] }
//           }
//         ]
//       },
//       // photovoltaic
//       {
//         path: '/photovoltaic',
//         name: 'photovoltaic',
//         redirect: '/photovoltaic/photovoltaicList',
//         component: RouteView,
//         meta: { title: 'menu.photovoltaic', icon: 'form', permission: ['dashboard'] },
//         children: [
//           {
//             path: '/photovoltaic/photovoltaicList',
//             name: 'photovoltaicList',
//             component: () => import('@/views/photovoltaic/photovoltaicList'),
//             meta: { title: 'menu.photovoltaic.photovoltaicList', keepAlive: false, permission: ['dashboard'] }
//           }
//         ]
//       },
//       // alarm
//       {
//         path: '/alarm',
//         name: 'alarm',
//         redirect: '/alarm/photovoltaic',
//         component: RouteView,
//         meta: { title: 'menu.alarm', icon: 'form', permission: ['dashboard'] },
//         children: [
//           {
//             path: '/alarm/photovoltaic',
//             name: 'photovoltaic',
//             component: () => import('@/views/alarm/Photovoltaic'),
//             meta: { title: 'menu.alarm.photovoltaic', keepAlive: false, permission: ['dashboard'] }
//           }, {
//             path: '/alarm/setting',
//             name: 'setting',
//             component: () => import('@/views/alarm/Setting'),
//             meta: { title: 'menu.alarm.setting', keepAlive: false, permission: ['dashboard'] }
//           }, {
//             path: '/alarm/alarmList',
//             name: 'alarmList',
//             component: () => import('@/views/alarm/AlarmList'),
//             meta: { title: 'menu.alarm.alarmList', keepAlive: false, permission: ['dashboard'] }
//           }, {
//             path: '/alarm/remindList',
//             name: 'remindList',
//             component: () => import('@/views/alarm/RemindList'),
//             meta: { title: 'menu.alarm.remindList', keepAlive: false, permission: ['dashboard'] }
//           }
//         ]
//       },
//       // system
//       {
//         path: '/system',
//         name: 'system',
//         redirect: '/system/userList',
//         component: RouteView,
//         meta: { title: 'menu.system', icon: 'form', permission: ['dashboard'] },
//         children: [
//           {
//             path: '/system/userList',
//             name: 'userList',
//             component: () => import('@/views/system/UserList'),
//             meta: { title: 'menu.system.userList', keepAlive: false, permission: ['dashboard'] }
//           }, {
//             path: '/system/meenList',
//             name: 'meenList',
//             component: () => import('@/views/system/MeenList'),
//             meta: { title: 'menu.system.meenList', keepAlive: false, permission: ['dashboard'] }
//           }, {
//             path: '/system/modelList',
//             name: 'modelList',
//             component: () => import('@/views/system/ModelList'),
//             meta: { title: 'menu.system.modelList', keepAlive: false, permission: ['dashboard'] }
//           }, {
//             path: '/system/RoleList',
//             name: 'roleList',
//             component: () => import('@/views/system/RoleList'),
//             meta: { title: 'menu.system.roleList', keepAlive: false, permission: ['dashboard'] }
//           }, {
//             path: '/system/actionList',
//             name: 'actionList',
//             component: () => import('@/views/system/ActionList'),
//             meta: { title: 'menu.system.actionList', keepAlive: false, permission: ['dashboard'] }
//           }
//         ]
//       },
//       // message
//       {
//         path: '/message',
//         name: 'message',
//         redirect: '/message/messageList',
//         component: RouteView,
//         meta: { title: 'menu.message', icon: 'form', permission: ['dashboard'] },
//         children: [
//           {
//             path: '/message/messageList',
//             name: 'messageList',
//             component: () => import('@/views/message/MessageList'),
//             meta: { title: 'menu.message.messageList', keepAlive: false, permission: ['dashboard'] }
//           }
//         ]
//       },
//       // system
//       {
//         path: '/setting',
//         name: 'setting',
//         redirect: '/setting/personalSettings',
//         component: RouteView,
//         meta: { title: 'menu.setting', icon: 'form', permission: ['dashboard'] },
//         children: [
//           {
//             path: '/setting/personalSettings',
//             name: 'personalSettings',
//             component: () => import('@/views/setting/PersonalSettings'),
//             meta: { title: 'menu.setting.personalSettings', keepAlive: false, permission: ['dashboard'] }
//           }, {
//             path: '/setting/changePassword',
//             name: 'changePassword',
//             component: () => import('@/views/setting/ChangePassword'),
//             meta: { title: 'menu.setting.changePassword', keepAlive: false, permission: ['dashboard'] }
//           }, {
//             path: '/setting/neutralManagement',
//             name: 'neutralManagement',
//             component: () => import('@/views/setting/NeutralManagement'),
//             meta: { title: 'menu.setting.neutralManagement', keepAlive: false, permission: ['dashboard'] }
//           }
//         ]
//       }
//     ]
//   },
//   {
//     path: '*',
//     redirect: '/404',
//     hidden: true
//   }
// ]

export const generatorStaticRouter = () => {

}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = token => {
  return new Promise((resolve, reject) => {
    loginService
      .getCurrentUserNav(token)
      .then(res => {
        // storage.set('user_id',res.data.id)
        // storage.commit('user_id',res.data.id)
        // const token = storage.get(ACCESS_TOKEN)
        // console.log('token:', token)
        const result = res
        var menus=[]
        // res.data.menus.forEach((element)=>{
        //   menus.push(element.name)
        // })
        // menus.splice(3,2)
        //  console.log('rootRouter',rootRouter)
        // rootRouter[0].children.forEach((element,index) => {
        //   // console.log(element.name)
        //   if(menus.indexOf(element.name)==-1){
        //     console.log(element.name)
        //     if(element.name!='dashboard'){
        //       rootRouter[0].children.splice(index,1)
        //     }
        //   }
        //   if(element.children.length>0){
        //     var childrens=element.children
        //     childrens.forEach((k,i)=>{
        //       if(menus.indexOf(k.name)==-1){
        //         console.log(k.name)
        //         element.children.splice(i,1)
        //       }
        //     })
        //   }
        // });


        const menuNav = []
        const childrenNav = []
        //      后端数据, 根级树数组,  根级 PID
        listToTree(result.data.menus, childrenNav, 0)
        // rootRouter.children = childrenNav
        // menuNav.push(rootRouter)
         console.log('childrenNav',childrenNav)
        const routers = generator(childrenNav)
        console.log('routers',routers)
        const rootRouter = {
          path: '/',
            name: 'index',
            component: BasicLayout,
            meta: { title: 'menu.home' },
            redirect: '/dashboard/workplace',
            children: [
              // dashboard
              // {
              //   path: '/dashboard',
              //   name: 'dashboard',
              //   redirect: '/dashboard/workplace',
              //   component: RouteView,
              //   meta: { title: 'menu.dashboard', keepAlive: true, icon: bxAnaalyse, permission: ['dashboard'] },
              //   children: [
              //     {
              //       path: '/dashboard/workplace',
              //       name: 'workplace',
              //       component: () => import('@/views/dashboard/Workplace'),
              //       meta: { title: 'menu.dashboard.workplace', keepAlive: true, permission: ['dashboard'] }
              //     }
              //   ]
              // },
              {
                path: '/dashboard/workplace',
                name: 'workplace',
                component: () => import('@/views/dashboard/Workplace'),
                meta: { title: 'menu.dashboard.workplace', keepAlive: true, permission: ['dashboard'] }
              }
            ]
        
        }
        console.log('rootRouter',rootRouter)
        routers.forEach((element)=>{
          rootRouter.children.push(element)
        })
        console.log('rootRouter',rootRouter)
        menuNav.push(rootRouter)
        // menuNav.push(notFoundRouter)
        console.log('格式化后最终',menuNav)
        // routers.push({
        //   path:"*",
        //   redirect:'/404'
        // })
        // const routers = rootRouter
        resolve(menuNav)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    var str=item.key
    var firstLetter = str.charAt(0).toUpperCase();  
    var restLetters = str.slice(1);  
    str=firstLetter + restLetters
  
    var url=''
    if(parent!=undefined){
      url=parent.path+'/'+str
    }
    let hasChildren = item.children && item.children.length > 0
    let component = {}
    if (hasChildren) {
      component = RouteView
    } else if (item.key) {
      component = () => import(`@/views${url}`)
    }
    const { title, show, hideChildren, hiddenHeaderContent, target, icon } = item || {}
    const currentRouter = {
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      path: item.path || `${(parent && parent.path) || ''}/${item.key}`,
      // 路由名称，建议唯一
      name: item.name || item.key || '',
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component || item.key],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      // component: (() => import(`@/views${url}`)),
      
      // component: () => import('@/views/form/basicForm'),
      
      // component: constantRouterComponents[item.key] || (() => import(`@/views/${item.component}`)),
      component :component,


      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: {
        title: item.title,
        icon: icon || undefined,
        // hiddenHeaderContent: hiddenHeaderContent,
        // target: target,
        // permission: item.name
      }
    }
    if (item.path == '/') {
      // console.log('currentRouter', currentRouter)
    }
    // 是否设置了隐藏菜单
    if (show === false) {
      currentRouter.hidden = true
    }
    // 是否设置了隐藏子菜单
    if (hideChildren) {
      currentRouter.hideChildrenInMenu = true
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      // Recursion
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}

/**
 * 数组转树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {
      const child = {
        ...item,
        key: item.key || item.name,
        children: []
      }
      // 迭代 list， 找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id)
      // 删掉不存在 children 值的属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // 加入到树中
      tree.push(child)
    }
  })
}
